<?php
declare (strict_types=1);

namespace app\api\controller;

use ffhome\frame\controller\BaseController;
use ffhome\upload\Uploadfile;
use think\App;

class Upload extends BaseController
{
    public function file()
    {
        $uploadConfig = sysConfig('upload');
        $data = [
            'upload_type' => $uploadConfig['upload_type'],
            'file' => $this->request->file('file'),
            'prefix' => 'up',
        ];
        $rule = [
            'upload_type|' . lang('upload.upload_type_fail') => "in:{$uploadConfig['upload_allow_type']}",
            'file|' . lang('upload.file') => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->setPrefix($data['prefix'])
                ->setCompress(false)
                ->setCreateBy(currentMember()['id'])
                ->save();
        } catch (\Exception $e) {
            $this->json_result('', $e->getMessage(), config('code.fail'));
        }
        if ($upload['save'] == true) {
            unset($upload['save']);
            $upload['url'] = sysValue('domain_name') . $upload['url'];
            $this->json_result($upload);
        } else {
            $this->json_result('', $upload['msg'], config('code.fail'));
        }
    }

    public function base64(string $img)
    {
        if (!preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)) {
            $this->json_result('', '数据错误', config('code.fail'));
        }
        $type = $result[2];
        if (!in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $this->json_result('', '数据格式错误', config('code.fail'));
        }
        $path = 'upload' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . date('Ymd');
        $fileName = uniqid() . '.' . $type;
        $absolutePath = public_path() . $path;
        if (!is_dir($absolutePath)) {
            mkdir($absolutePath, 0777, true);
        }
        if (!file_put_contents($absolutePath . DIRECTORY_SEPARATOR . $fileName,
            base64_decode(str_replace($result[1], '', $img)))) {
            $this->json_result('', '图片上传失败', config('code.fail'));
        }
        $fileName = '/' . str_replace('\\', '/', $path) . '/' . $fileName;
        $this->json_result(['path' => $fileName]);
    }
}